package com.fiberhome.opticalbox.ui;

import java.util.Arrays;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.BaseActivity;
import com.fiberhome.opticalbox.C;
import com.fiberhome.opticalbox.net.NetConstant;
import com.fiberhome.opticalbox.net.NetManager.TcpErrorListener;
import com.fiberhome.opticalbox.net.NetManager.TcpListener;
import com.fiberhome.opticalbox.net.bean.Parameter;
import com.fiberhome.opticalbox.net.utils.JsonUtil;
import com.fiberhome.opticalbox.ui.SurfCtrlActivity.SurfCtrlInfo;
import com.fiberhome.opticalbox.utils.LogUtil;
import com.fiberhome.opticalbox.utils.NetworkUtil;
import com.fiberhome.opticalbox.view.third.wheel.WheelView;
import com.fiberhome.opticalbox.view.third.wheel.WheelView.OnWheelViewListener;

/**
 * 绿色上网
 * 
 * @author wangpeng
 * 
 */
public class SurfCtrlSettingsActivity extends BaseActivity {

	private View layWrapName;
	private EditText edName;
	private ImageView imgIcoName;
	private TextView txTimeLimit, txTimeStart, txTimeEnd;

	public static final int TYPE_START = 1;
	public static final int TYPE_END = 2;
	private int startHour, startMin, endHour, endMin;
	private String dayOfWeek;
	private String MAC;
	private String HostName;

	private Dialog dlgResetDay, dlgResetTime;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.ob_activity_surf_ctrl_settings);
		super.onCreate(savedInstanceState);
		startHour = getIntent().getIntExtra(C.bundle.startHour, 6);
		startMin = getIntent().getIntExtra(C.bundle.startMin, 0);
		endHour = getIntent().getIntExtra(C.bundle.endHour, 21);
		endMin = getIntent().getIntExtra(C.bundle.endMin, 0);
		dayOfWeek = getIntent().getStringExtra(C.bundle.dayOfWeek);
		if (TextUtils.isEmpty(dayOfWeek) || dayOfWeek.length() != 7) {
			dayOfWeek = "0000000";
		}

		titleView.setTitle(R.string.ob_settings);
		titleView.setBackground(R.drawable.ob_bg_title);
		titleView.addLeftDrawableMenu(this, R.drawable.ob_ico_back, 15, 25, onBackClickListener);

		findViewById(R.id.btn_save).setOnClickListener(onSaveClickListener);

		layWrapName = findViewById(R.id.lay_wrap_name);
		edName = (EditText) findViewById(R.id.ed_name);
		imgIcoName = (ImageView) findViewById(R.id.img_ico_name);
		edName.setOnFocusChangeListener(onEditTextFocusChangeListener);

		findViewById(R.id.lay_time_limit).setOnClickListener(onParamSetClickListener);
		findViewById(R.id.lay_time_start).setOnClickListener(onParamSetClickListener);
		findViewById(R.id.lay_time_end).setOnClickListener(onParamSetClickListener);
		txTimeLimit = (TextView) findViewById(R.id.tx_time_limit);
		txTimeStart = (TextView) findViewById(R.id.tx_time_start);
		txTimeEnd = (TextView) findViewById(R.id.tx_time_end);

		dealTimeInfo(txTimeStart, startHour, startMin);
		dealTimeInfo(txTimeEnd, endHour, endMin);
		txTimeLimit.setText(convertDayInfo1(dayOfWeek));

		MAC = getIntent().getStringExtra(C.bundle.mac);
		HostName = getIntent().getStringExtra(C.bundle.hostName);
		if (!TextUtils.isEmpty(MAC)) {
			String nickname = new SurfCtrlInfo(MAC, HostName).getNickName();

			if (TextUtils.isEmpty(nickname)) {
				nickname = HostName;
			}

			edName.setText(nickname);
			edName.setSelection(edName.getText().toString().length());
			edName.clearFocus();
		} else {
			showToast(R.string.ob_fail_get_device_mac);
			finish();
		}

		registerChildTcpListener(tcpListener);
		registerChildTcpErrorListener(tcpErrorListener);
	}

	private void dealTimeInfo(TextView textView, int hour, int min) {
		if (hour < 0 || min < 0) {
			LogUtil.e("SurfCtrlSettingsActivity dealTimeInfo() error params");
			return;
		}
		String strHour = hour < 10 ? "0" + hour : "" + hour;
		String strMin = min < 10 ? "0" + min : "" + min;
		textView.setText(strHour + ":" + strMin);
	}

	private String convertDayInfo1(String dayOfWeeks) {
		String[] day = getResources().getStringArray(R.array.ob_surf_ctrl_day);
		String interval = " ";
		String result = "";
		if ("1111111".equals(dayOfWeeks)) {
			result = getString(R.string.ob_time_limit_1);
		} else if ("0000000".equals(dayOfWeeks)) {
			result = getString(R.string.ob_time_no_limit);
		} else {
			byte[] daysInfo = dayOfWeeks.getBytes();
			if (daysInfo != null && daysInfo.length > 0) {
				for (int i = 0; i < daysInfo.length; i++) {
					if ('1' == daysInfo[i]) {
						result += getString(R.string.ob_week_) + day[i] + interval;
					}
				}
				result = result.substring(0, result.length() - interval.length());
			}
		}
		return result;
	}

	private OnFocusChangeListener onEditTextFocusChangeListener = new OnFocusChangeListener() {
		@Override public void onFocusChange(View view, boolean hasFocus) {
			layWrapName.setBackgroundResource(hasFocus ? R.drawable.ob_border_n_ff00aef1 : R.drawable.ob_border_n_ffe1e1e1);
			imgIcoName.setImageResource(hasFocus ? R.drawable.ob_edit_user_pressed : R.drawable.ob_edit_user_normal);
		}
	};

	private OnClickListener onParamSetClickListener = new OnClickListener() {
		@Override public void onClick(View view) {
			switch (view.getId()) {
			case R.id.lay_time_limit:
				showLimitDayDialog();
				break;
			case R.id.lay_time_start:
				showLimitTimeDialog(TYPE_START);
				break;
			case R.id.lay_time_end:
				showLimitTimeDialog(TYPE_END);
				break;
			}
		};
	};

	private void showLimitDayDialog() {
		View content = inflater.inflate(R.layout.ob_dialog_part_surf_ctrl_settings_limit_day, null);
		final CheckBox ckDay1 = (CheckBox) content.findViewById(R.id.ck_day1);
		final CheckBox ckDay2 = (CheckBox) content.findViewById(R.id.ck_day2);
		final CheckBox ckDay3 = (CheckBox) content.findViewById(R.id.ck_day3);
		final CheckBox ckDay4 = (CheckBox) content.findViewById(R.id.ck_day4);
		final CheckBox ckDay5 = (CheckBox) content.findViewById(R.id.ck_day5);
		final CheckBox ckDay6 = (CheckBox) content.findViewById(R.id.ck_day6);
		final CheckBox ckDay7 = (CheckBox) content.findViewById(R.id.ck_day7);
		View.OnClickListener onClickListener = new OnClickListener() {
			@Override public void onClick(View view) {
				switch (view.getId()) {
				case R.id.lay_day1:
					ckDay1.setChecked(!ckDay1.isChecked());
					break;
				case R.id.lay_day2:
					ckDay2.setChecked(!ckDay2.isChecked());
					break;
				case R.id.lay_day3:
					ckDay3.setChecked(!ckDay3.isChecked());
					break;
				case R.id.lay_day4:
					ckDay4.setChecked(!ckDay4.isChecked());
					break;
				case R.id.lay_day5:
					ckDay5.setChecked(!ckDay5.isChecked());
					break;
				case R.id.lay_day6:
					ckDay6.setChecked(!ckDay6.isChecked());
					break;
				case R.id.lay_day7:
					ckDay7.setChecked(!ckDay7.isChecked());
					break;
				}
			}
		};
		content.findViewById(R.id.lay_day1).setOnClickListener(onClickListener);
		content.findViewById(R.id.lay_day2).setOnClickListener(onClickListener);
		content.findViewById(R.id.lay_day3).setOnClickListener(onClickListener);
		content.findViewById(R.id.lay_day4).setOnClickListener(onClickListener);
		content.findViewById(R.id.lay_day5).setOnClickListener(onClickListener);
		content.findViewById(R.id.lay_day6).setOnClickListener(onClickListener);
		content.findViewById(R.id.lay_day7).setOnClickListener(onClickListener);

		ckDay1.setChecked("1".equals(dayOfWeek.substring(0, 1)));
		ckDay2.setChecked("1".equals(dayOfWeek.substring(1, 2)));
		ckDay3.setChecked("1".equals(dayOfWeek.substring(2, 3)));
		ckDay4.setChecked("1".equals(dayOfWeek.substring(3, 4)));
		ckDay5.setChecked("1".equals(dayOfWeek.substring(4, 5)));
		ckDay6.setChecked("1".equals(dayOfWeek.substring(5, 6)));
		ckDay7.setChecked("1".equals(dayOfWeek.substring(6, 7)));

		dlgResetDay = dialogUtil.createBottom(content, true, true).setTitleText(R.string.ob_repeat)
				.setConfirmListener(new OnClickListener() {
					@Override public void onClick(View v) {
						dayOfWeek = "";
						dayOfWeek += ckDay1.isChecked() ? "1" : "0";
						dayOfWeek += ckDay2.isChecked() ? "1" : "0";
						dayOfWeek += ckDay3.isChecked() ? "1" : "0";
						dayOfWeek += ckDay4.isChecked() ? "1" : "0";
						dayOfWeek += ckDay5.isChecked() ? "1" : "0";
						dayOfWeek += ckDay6.isChecked() ? "1" : "0";
						dayOfWeek += ckDay7.isChecked() ? "1" : "0";
						dlgResetDay.dismiss();
						txTimeLimit.setText(convertDayInfo1(dayOfWeek));
					}
				}).show();
	}

	private void showLimitTimeDialog(final int type) {
		View content = inflater.inflate(R.layout.ob_dialog_part_surf_ctrl_settings_limit_time, null);
		WheelView wheelHour = (WheelView) content.findViewById(R.id.wheel_hour);
		wheelHour.setOffset(2);
		wheelHour.setItems(Arrays.asList(getWheelContent(0, 24)));
		wheelHour.setOnWheelViewListener(new OnWheelViewListener() {
			@Override public void onSelected(int selectedIndex, String item) {
				if (type == TYPE_START) {
					startHour = Integer.valueOf(item);
				} else if (type == TYPE_END) {
					endHour = Integer.valueOf(item);
				}
			}
		});
		WheelView wheelMin = (WheelView) content.findViewById(R.id.wheel_min);
		wheelMin.setOffset(2);
		wheelMin.setItems(Arrays.asList(getWheelContent(0, 60)));
		wheelMin.setOnWheelViewListener(new OnWheelViewListener() {
			@Override public void onSelected(int selectedIndex, String item) {
				if (type == TYPE_START) {
					startMin = Integer.valueOf(item);
				} else if (type == TYPE_END) {
					endMin = Integer.valueOf(item);
				}
			}
		});

		if (type == TYPE_START) {
			wheelHour.setSeletion(startHour);
			wheelMin.setSeletion(startMin);
		} else if (type == TYPE_END) {
			wheelHour.setSeletion(endHour);
			wheelMin.setSeletion(endMin);
		}

		dlgResetTime = dialogUtil.createBottom(content, true, true).setTitleText(R.string.ob_time_settings)
				.setConfirmListener(new OnClickListener() {
					@Override public void onClick(View v) {
						dlgResetTime.dismiss();
						dealTimeInfo(txTimeStart, startHour, startMin);
						dealTimeInfo(txTimeEnd, endHour, endMin);
					}
				}).show();
	}

	private String[] getWheelContent(int start, int num) {
		if (start < 0 || num < 0) {
			return null;
		}
		String[] content = new String[num];
		for (int i = start; i < content.length; i++) {
			content[i] = (i < 10 ? "0" : "") + String.valueOf(i);
		}
		return content;
	}

	private OnClickListener onSaveClickListener = new OnClickListener() {
		@Override public void onClick(View v) {
			requestSetAttachDeviceInfo();
		}
	};

	private void requestSetAttachDeviceInfo() {
		new SurfCtrlInfo(MAC, HostName).saveNickName(edName.getText().toString());
		String InternetAccessRight = "0000000".equals(dayOfWeek) ? "OFF" : "ON";
		String StartTime = (startHour < 10 ? "0" + startHour : startHour) + ":" + (startMin < 10 ? "0" + startMin : startMin);
		String EndTime = (endHour < 10 ? "0" + endHour : endHour) + ":" + (endMin < 10 ? "0" + endMin : endMin);
		netManager.sendTcp(JsonUtil.get_SET_ATTACH_DEVICE_RIGHT(MAC, InternetAccessRight, StartTime, EndTime, dayOfWeek, ""));
	}

	private TcpListener tcpListener = new TcpListener() {
		@Override public void onReceive(String cmdType, Parameter param) {
			if (NetConstant.SET_ATTACH_DEVICE_RIGHT.equals(cmdType)) {
				finish();
			}
		}
	};

	private TcpErrorListener tcpErrorListener = new TcpErrorListener() {
		@Override public void onError(String cmdType) {
			if (NetConstant.SET_ATTACH_DEVICE_RIGHT.equals(cmdType)) {
			}
			showToast(NetworkUtil.isDisconnected(SurfCtrlSettingsActivity.this) ? R.string.ob_error_net : R.string.ob_error_request);
		}
	};
}